package com.zhouyibike.uu.ui.activity.mybike;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.tencent.mm.opensdk.constants.Build;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.zhouyibike.uu.R;
import com.zhouyibike.uu.config.Config;
import com.zhouyibike.uu.entity.GetCodeResult;
import com.zhouyibike.uu.entity.PayResult;
import com.zhouyibike.uu.entity.YiBuyBicycleResult;
import com.zhouyibike.uu.http.ApiCallback;
import com.zhouyibike.uu.ui.activity.web.TotalWebActivity;
import com.zhouyibike.uu.ui.base.BaseActivity;

import java.util.HashMap;
import java.util.Map;

import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import de.greenrobot.event.ThreadMode;

public class HaoyouZhuanzengActivity extends BaseActivity implements View.OnClickListener, CompoundButton.OnCheckedChangeListener {
    private ImageButton mBtnBack;
    private TextView mBtnTitle;
    private Button btn_succ;
    private CheckBox rbtn_loginactivity_isagree;
    private CheckBox cb_wx,cb_zfb;
    private String paytype="1";
    private TextView gofukuan,zhuanzengpricetv,tv_agreement;
    private int totalnum;
    private double zhuanzengprice;
    private EditText zhuanzengnumtv,zhuanzengnum,zhuanzengname;
    private int zhuanzengingnum;
    private String name,number;
    private IWXAPI api;
    private LinearLayout weixinly,zhifubaoly;
//    intent3.putExtra("cansellnum", totalnum);
//    intent3.putExtra("zhuanzengprice", zhuanzengprice);
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_haoyouzhuanzeng);
        EventBus.getDefault().register(this);
        api = WXAPIFactory.createWXAPI(this, null);
        totalnum=getIntent().getIntExtra("cansellnum", 0);
        zhuanzengprice=getIntent().getDoubleExtra("zhuanzengprice",0);
        initView();
        initlistener();
    }

    private void initlistener() {
        cb_wx.setClickable(false);
        cb_zfb.setClickable(false);
        rbtn_loginactivity_isagree.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (rbtn_loginactivity_isagree.isChecked())
                {
                    gofukuan.setEnabled(true);
                }else{
                    gofukuan.setEnabled(false);
                }
            }
        });
        gofukuan.setOnClickListener(this);
        weixinly.setOnClickListener(this);
        zhifubaoly.setOnClickListener(this);
        tv_agreement.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getWZMsg("10","单车转赠协议");
            }
        });
    }

    private void initView(){
        tv_agreement= (TextView) findViewById(R.id.tv_agreement);
        weixinly= (LinearLayout) findViewById(R.id.weixinly);
        zhifubaoly= (LinearLayout) findViewById(R.id.zhifubaoly);
        zhuanzengnum= (EditText) findViewById(R.id.zhuanzengnum);
        zhuanzengname= (EditText) findViewById(R.id.zhuanzengname);
        zhuanzengnumtv= (EditText) findViewById(R.id.zhuanzengnumtv);
        rbtn_loginactivity_isagree= (CheckBox) findViewById(R.id.rbtn_loginactivity_isagree);
        gofukuan= (TextView) findViewById(R.id.gofukuan);
        gofukuan.setClickable(true);
        cb_wx= (CheckBox) findViewById(R.id.cb_chongzhi_wx);
        cb_zfb= (CheckBox) findViewById(R.id.cb_chongzhi_zfb);
        mBtnBack = (ImageButton) findViewById(R.id.bar_btn_back);
        mBtnTitle = (TextView) findViewById(R.id.bar_text_title);
        mBtnTitle.setText("好友转赠");
        mBtnBack.setOnClickListener(this);
        zhuanzengpricetv= (TextView) findViewById(R.id.zhuanzengprice);
        zhuanzengnumtv.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                int num= 0;
                try {
                    num = Integer.parseInt(zhuanzengnumtv.getText().toString());
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                    num=0;
                }
                zhuanzengingnum=num;
                zhuanzengpricetv.setText(String.format("%.2f",(num*zhuanzengprice)));
            }
        });
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bar_btn_back:
                finish();
                break;
            case R.id.weixinly:
                cb_zfb.setChecked(false);
                cb_wx.setChecked(true);
                paytype="1";
                break;
            case R.id.zhifubaoly:
                cb_zfb.setChecked(true);
                cb_wx.setChecked(false);
                paytype="2";
                break;
            case R.id.gofukuan:
                try {
                    name=zhuanzengname.getText().toString();
                } catch (Exception e) {
                    e.printStackTrace();
                    name="";
                }
                try {
                    number=zhuanzengnum.getText().toString();
                } catch (Exception e) {
                    e.printStackTrace();
                    number="";
                }
//                if (paytype.equals("1"))
//               {
//                   toastShow("微信");
//               }
//                if (paytype.equals("2"))
//                {
//                    toastShow("支付宝");
//                }
                chongzhi();
                break;
        }
    }
    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        switch (buttonView.getId()){
            case R.id.cb_chongzhi_wx:
                if(isChecked){
                    cb_zfb.setChecked(false);
                    paytype="1";
                }else{
                    cb_zfb.setChecked(true);
                    paytype="2";
                }
                break;
            case R.id.cb_chongzhi_zfb:
                if(isChecked){
                    cb_wx.setChecked(false);
                    paytype="2";
                }else{
                    cb_wx.setChecked(true);
                    paytype="1";
                }
                break;
        }
    }
    private void wxpay(YiBuyBicycleResult.DataBean.WeChatPayBean model) {
        api.registerApp(model.getAppId());
        boolean isPaySupported = api.getWXAppSupportAPI() >= Build.PAY_SUPPORTED_SDK_INT;
        if (!isPaySupported) {
            Toast.makeText(HaoyouZhuanzengActivity.this, "您的微信版本太低，不支持支付功能", Toast.LENGTH_SHORT).show();
            return;
        }
        Toast.makeText(HaoyouZhuanzengActivity.this, "获取订单中...", Toast.LENGTH_SHORT).show();
        try {
            PayReq request = new PayReq();

            request.appId = model.getAppId();

            request.partnerId = model.getPartnerId();

            request.prepayId = model.getPrepayId();

            request.packageValue = model.getPackageX();

            request.nonceStr = model.getNoncestr();

            request.timeStamp = model.getTimestamp();

            request.sign = model.getSign();

            api.sendReq(request);

        } catch (Exception e) {
            Toast.makeText(HaoyouZhuanzengActivity.this, "异常：" + e.getMessage(), Toast.LENGTH_SHORT).show();
        }

    }

    @Subscribe(threadMode = ThreadMode.MainThread)
    public void wxpayresult(Integer progress) {
        if (progress == 0) {//支付成功
            paysuccess();
        } else {
            Toast.makeText(HaoyouZhuanzengActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
        }
    }

    private void zfbpay(final String orderinfo) {

        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                PayTask alipay = new PayTask(HaoyouZhuanzengActivity.this);
                Map<String, String> result = alipay.payV2(orderinfo, true);
                Log.i("msp", result.toString());

                Message msg = new Message();
                msg.what = 1;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (resultStatus.equals("9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        paysuccess();
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        Toast.makeText(HaoyouZhuanzengActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
                    }
                    break;
                }

                default:
                    break;
            }
        }
    };

    private void paysuccess() {
//        setResult(1);
        toastShow("转赠成功");
//        intent.putExtra("payamont",payamont);
//        startActivityForResult(intent,400);
        Intent i=new Intent(this,ZZSuccessActivity.class);
        startActivityForResult(i,101);//支付成功
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode==101&&resultCode==101)
        {
            setResult(101);//关闭上一界面
            finish();
        }
    }

    private void chongzhi(){
        Map<String, String> params = new HashMap<>();
        params.put("token", preferences.getString("token",""));
        params.put("userName",name);
        params.put("phoneNumber",number);
        params.put("amount",zhuanzengingnum+"");
        showProgressDialog();
        addSubscription(apiStores.TransferBikeForFree(params),
                new ApiCallback<YiBuyBicycleResult>() {

                    @Override
                    public void onSuccess(YiBuyBicycleResult model) {
                        if (model.getStatus() == Config.SUCCESSCODE) {
//                            paysuccess();
                            if (paytype.equals("2")) {//支付宝
                                zfbpay(model.getData().getAlipay());
                            } else {
//                                model.getData().getWeChatPay();
//                                model.getData().getWeChat();
                                wxpay(model.getData().getWeChatPay());
                            }
                        } else {
                            toastShow(model.getMessage());
                        }
                    }

                    @Override
                    public void onFailure(String msg) {
                        toastShow(msg);

                    }

                    @Override
                    public void onFinish() {
                        dismissProgressDialog();
                    }
                });
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
    private void getWZMsg(String type, final String name) {
        Map<String, String> params = new HashMap<>();
        params.put("token", preferences.getString("token", ""));
        params.put("type", type);
        showProgressDialog();
        addSubscription(apiStores.GetInformationzcxy(params),
                new ApiCallback<GetCodeResult>() {

                    @Override
                    public void onSuccess(GetCodeResult model) {
                        if (model.getStatus() == Config.SUCCESSCODE) {
                            Intent i = new Intent(HaoyouZhuanzengActivity.this, TotalWebActivity.class);
                            i.putExtra("title", name);
                            i.putExtra("url", model.getData());
                            startActivity(i);
                        } else {
                            toastShow(model.getMessage());
                        }
                    }

                    @Override
                    public void onFailure(String msg) {
                        toastShow(msg);
                    }

                    @Override
                    public void onFinish() {
                        dismissProgressDialog();
                    }
                });
    }
}
